<template>
  <div class="article-detail" v-if="article">
    <!-- 返回按钮 -->
    <div class="top-bar">
      <button class="back-btn" @click="goBack">← 返回</button>
      <el-dropdown trigger="click" @command="handleMenuCommand">
        <span class="more-btn">···</span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="report">举报</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <h2 class="article-title">{{ article.title }}</h2>

    <!-- 作者信息模块 -->
    <div class="author-info">
      <!-- 第一行：头像 + 作者昵称 + 发布时间 + 关注按钮 -->
      <div class="author-top-row">
        <img
          class="avatar"
          :src="article.authorAvatar"
          alt="作者头像"
          @click="goUserProfile(article.authorId)"
        />

        <div class="author-text">
          <div class="name">{{ article.authorName }}</div>
          <div class="publish-time">{{ formatTime(article.createTime) }}</div>
        </div>

        <button
          class="follow-btn"
          :class="{ followed: article.isFollowed }"
          @click="toggleFollow"
        >
          {{ article.isFollowed ? '已关注' : '+ 关注' }}
        </button>
      </div>

      <!-- 第二行：话题标签 -->
      <div class="topic-tags">
        <span
          class="topic"
          v-for="topic in article.topics"
          :key="topic.topicId"
          @click="goTopic(topic.topicId)"
        >
          #{{ topic.topicName }}
        </span>
      </div>
    </div>

    <!-- 正文内容模块 -->
    <div class="article-content">
      <div
        v-for="item in contentList"
        :key="item.orderIndex"
        class="content-block"
      >
        <p v-if="item.contentType === 1" class="text">
          {{ item.textContent }}
        </p>
        <img
          v-else-if="item.contentType === 2"
          :src="item.imageUrl"
          class="image"
          alt="插图"
        />
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comment-section">
      <div class="comment-title-wrapper">
        <h3 class="comment-title">全部评论 {{ article.commentCount }}</h3>
      </div>

      <!-- 使用递归组件 -->
      <CommentItem
        v-for="comment in comments"
        :key="comment.commentId"
        :comment="comment"
        :is-reply="false"
        @like="toggleLike"
        @select="handleSelect"
      />
    </div>

    <!-- 自定义弹窗 -->
    <teleport to="body">
      <div v-if="showDialog" class="custom-dialog-mask">
        <div class="custom-dialog">
          <p class="dialog-text">
            你确定要{{ dialogActionText }} {{ article.authorName }} 吗？
          </p>
          <div class="dialog-buttons">
            <button @click="handleDialogConfirm" class="confirm-btn">
              确认
            </button>
            <button @click="handleDialogCancel" class="cancel-btn">取消</button>
          </div>
        </div>
      </div>
    </teleport>

    <!-- 评论输入区域 -->
    <div class="link-reply__main-box">
      <!-- 新增回复预览 -->
      <div v-if="selectedComment" class="reply-preview">
        <div class="preview-content">
          <span class="reply-target"
            >回复 @{{ selectedComment.username }}：</span
          >
          <span class="original-comment">{{
            selectedComment.commentContent
          }}</span>
          <button @click="selectedComment = null" class="cancel-reply">
            ×
          </button>
        </div>
      </div>
      <div class="link-reply__input-wrapper">
        <div
          class="link-reply__editor"
          contenteditable="true"
          @input="handleInput"
          ref="editorRef"
          :class="{ expanded: editorExpanded }"
          @focus="expandEditor"
          @blur="shrinkEditor"
        ></div>
        <div v-if="!newComment" class="link-reply__placeholder">参与讨论</div>
        <div class="link-reply__operation-box">
          <template v-if="!editorExpanded">
            <button
              class="link-reply__operation-item"
              @click.stop="toggleArticleLike"
            >
              <img
                :src="article.isLiked ? likeBlack : likeWhite"
                class="like-icon"
              />
              <span class="link-reply__operation-desc">
                {{ article.likeCount }}
              </span>
            </button>
            <button
              class="link-reply__operation-item"
              @click.stop="toggleFavorite"
            >
              <img
                :src="article.isFavorite ? starBlack : starWhite"
                class="like-icon"
              />
              <span class="link-reply__operation-desc">
                {{ article.favCount }}
              </span>
            </button>
            <button
              class="link-reply__operation-item"
              @click="expandCommentEditor"
            >
              <img src="@/assets/imgs/comment-icon.png" class="like-icon" />
              <span class="link-reply__operation-desc">{{
                article.commentCount
              }}</span>
            </button>
          </template>
          <template v-else>
            <button class="link-reply__operation-item" @click="submitComment">
              <i class="hb-icon">💬</i>
              <span class="link-reply__operation-desc">发布</span>
            </button>
            <button class="link-reply__operation-item" @click="cancelComment">
              <i class="hb-icon">❌</i>
              <span class="link-reply__operation-desc">取消</span>
            </button>
          </template>
        </div>
      </div>
    </div>
  </div>
  <ReportDialog v-model="showReportDialog" @submit="handleReportSubmit" />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getArticleDetail } from '@/apis/article'
import dayjs from 'dayjs'
import likeBlack from '@/assets/imgs/like-black.png'
import likeWhite from '@/assets/imgs/like-white.png'
import starBlack from '@/assets/imgs/star-black.png'
import starWhite from '@/assets/imgs/star-white.png'
import { getComments, postComment } from '@/apis/comment'
import { likeTarget } from '@/apis/like'
import { favTarget } from '@/apis/fav'
import { followUser } from '@/apis/user'
import CommentItem from '@/views/Article/components/CommentItem.vue'
import ReportDialog from '@/components/ReportDialog.vue'
import { reportTarget as doReport } from '@/apis/report'

// 路由参数获取 articleId
const route = useRoute()
const router = useRouter()
const articleId = route.params.articleId

// 响应式数据
const article = ref(null)
const contentList = ref([])

// 加载数据
const fetchArticleDetail = async () => {
  try {
    const res = await getArticleDetail(articleId)
    article.value = res.data
    contentList.value = res.data.contentList || []
  } catch (err) {
    console.error('获取文章详情失败:', err)
  }
}

const formatTime = (time) => {
  const now = dayjs()
  const commentTime = dayjs(time)
  const diffMinutes = now.diff(commentTime, 'minute')
  if (diffMinutes < 1) return '刚刚'
  if (diffMinutes < 60) return `${diffMinutes}分钟前`
  if (diffMinutes < 1440) return `${Math.floor(diffMinutes / 60)}小时前`
  return commentTime.format('YYYY-MM-DD')
}

// 评论功能
const comments = ref([])
const editorRef = ref(null)
const editorExpanded = ref(false)
const newComment = ref(false)

// 输入框交互
const expandEditor = () => {
  editorExpanded.value = true
}

const expandCommentEditor = () => {
  editorExpanded.value = true
  nextTick(() => {
    editorRef.value?.focus()
  })
}

const shrinkEditor = () => {
  if (!newComment.value) {
    editorExpanded.value = false
  }
}
const handleInput = () => {
  newComment.value = editorRef.value.innerText.trim().length > 0
}
const selectedComment = ref(null)
const submitComment = async () => {
  console.log(article.value)
  if (newComment.value) {
    try {
      const content = editorRef.value.innerText.trim()
      const params = {
        targetType: selectedComment.value ? 3 : 2, // 文章评论为2，回复评论为3
        targetId: selectedComment.value
          ? selectedComment.value.commentId
          : article.value.articleId, // 文章ID
        content,
        parentCommentId: selectedComment.value?.commentId || null, // 父评论ID
        targetUserId:
          selectedComment.value?.commentUserId || article.value.authorId, // 被回复用户ID
      }

      await postComment(params)
      editorRef.value.innerText = ''
      newComment.value = false
      selectedComment.value = null
      await fetchComments()
    } catch (error) {
      console.error('发布评论失败:', error)
    }
  }
}

const handleSelect = (comment) => {
  if (selectedComment.value?.commentId === comment.commentId) {
    selectedComment.value = null
  } else {
    selectedComment.value = comment
    editorExpanded.value = true
    nextTick(() => editorRef.value.focus())
  }
}
const cancelComment = () => {
  editorRef.value.innerText = ''
  newComment.value = false
  editorExpanded.value = false
}

const fetchComments = async () => {
  const res = await getComments(route.params.articleId, 2)
  if (res.code === '200') comments.value = res.data
}

// 初始化
onMounted(async () => {
  fetchArticleDetail()
  await fetchComments()
  console.log(comments.value)
})

// 返回按钮
const goBack = () => router.back()

// 点赞功能
const toggleLike = async (comment) => {
  try {
    const newStatus = !comment.isLiked
    await likeTarget(comment.commentId, 3, newStatus)
    comment.isLiked = newStatus
    comment.commentLikesCount += newStatus ? 1 : -1
  } catch (error) {
    console.error('点赞操作失败:', error)
  }
}

const toggleArticleLike = async () => {
  try {
    const newStatus = !article.value.isLiked
    await likeTarget(article.value.articleId, 2, newStatus) // targetType=2表示文章
    article.value.isLiked = newStatus
    article.value.likeCount += newStatus ? 1 : -1
  } catch (error) {
    console.error('动态点赞失败:', error)
  }
}

const toggleFavorite = async () => {
  try {
    const newStatus = !article.value.isFavorite
    // 假设收藏使用相同API，需确认后端接口
    await favTarget(article.value.articleId, 2, newStatus)
    article.value.isFavorite = newStatus
    article.value.favCount += newStatus ? 1 : -1
  } catch (error) {
    console.error('收藏操作失败:', error)
  }
}
//关注
const showDialog = ref(false)
const dialogActionText = ref('关注') // or '取消关注'
let nextFollowStatus = false // 临时变量保存下一状态

const toggleFollow = () => {
  // 设置状态并弹出弹窗
  nextFollowStatus = !article.value.isFollowed
  dialogActionText.value = nextFollowStatus ? '关注' : '取消关注'
  showDialog.value = true
}

const handleDialogCancel = () => {
  showDialog.value = false
}

const handleDialogConfirm = async () => {
  showDialog.value = false
  try {
    const res = await followUser(article.value.authorId, nextFollowStatus)
    if (res.code === '200') {
      article.value.isFollowed = nextFollowStatus
      ElMessage.success(`${dialogActionText.value}成功`)
    } else if (res.code === 'A0220') {
      ElMessage.warning('自己不能关注自己哦')
    } else {
      ElMessage.error(`${dialogActionText.value}失败，请稍后再试`)
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    ElMessage.error('操作异常，请稍后重试')
  }
}

const goUserProfile = (userId) => {
  router.push(`/home/user/${userId}`)
}
const goTopic = (topicId) => {
  router.push(`/home/topic/${topicId}`)
}

const showReportDialog = ref(false)
const reportTargetInfo = ref({}) // 保存举报目标信息
const handleMenuCommand = (command) => {
  if (command === 'report') {
    reportTargetInfo.value = {
      targetId: article.value.articleId,
      targetType: 2, // 表示举报文章
    }
    showReportDialog.value = true
  }
}

const handleReportSubmit = async (payload) => {
  const data = {
    ...reportTargetInfo.value,
    ...payload,
  }
  try {
    const res = await doReport(data)
    if (res.code === '200') {
      ElMessage.success('举报成功，我们会尽快处理')
    } else {
      ElMessage.error(res.message || '举报失败')
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('网络异常，举报失败')
  }
}
</script>

<style scoped>
.article-detail {
  padding: 24px;
  max-width: 800px;
  margin: 0 auto;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.article-title {
  font-size: 24px;
  margin-bottom: 20px;
  text-align: center;
}

/* 作者信息区域 */
.author-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 24px;
}

.author-top-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 12px;
}

.author-text {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.name {
  font-size: 14px;
  font-weight: bold;
}

.publish-time {
  font-size: 12px;
  color: #888;
  margin-top: 4px;
}

.follow-btn {
  background-color: black;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  font-size: 14px;
  height: 32px;
  white-space: nowrap;
}

.topic-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-left: 60px; /* 对齐文字部分 */
}

.topic {
  background: #f0f2f5;
  color: #007bff;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 13px;
}

/* 正文内容区域 */
.article-content {
  margin-top: 24px;
}

.content-block {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  overflow: hidden; /* 隐藏溢出部分 */
  max-height: 600px; /* 根据需求设置最大高度 */
  margin: 12px 0; /* 添加垂直间距 */
}

.text {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
}

.image {
  width: auto; /* 宽度自动适应 */
  height: auto; /* 高度自动适应 */
  max-width: 100%; /* 最大宽度不超过容器 */
  max-height: 100%; /* 最大高度不超过容器 */
  object-fit: contain; /* 等比例缩放保持完整 */
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 可选：添加阴影提升层次感 */
}

/* 评论输入框 */
.comment-input-box {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 16px;
}

.comment-textarea {
  width: 100%;
  height: 80px;
  resize: none;
  padding: 10px;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 6px;
  box-sizing: border-box;
  font-family: inherit;
}

.comment-submit {
  margin-top: 10px;
  text-align: right;
}

.comment-submit button {
  padding: 6px 14px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.comment-submit button:hover {
  background-color: #0056b3;
}
.link-reply__main-box {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  max-width: 700px; /* 限制宽度与 home-main 匹配 */
  padding: 12px 16px;
  background-color: #fff;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.link-reply__input-wrapper {
  position: relative;
  background-color: #f7f8f9;
  border-radius: 8px;
  padding: 12px;
  min-height: 40px;
  transition: all 0.3s ease;
}

.link-reply__editor {
  outline: none;
  min-height: 30px;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  padding-right: 120px;
  transition: all 0.3s ease;
}

.link-reply__editor.expanded {
  min-height: 80px;
  padding-right: 120px;
}

.link-reply__placeholder {
  position: absolute;
  left: 14px;
  top: 12px;
  color: #aaa;
  pointer-events: none;
  font-size: 14px;
}

.link-reply__operation-box {
  position: absolute;
  right: 12px;
  bottom: 12px;
  display: flex;
  gap: 12px;
  align-items: center;
}

.link-reply__operation-item {
  display: flex;
  align-items: center;
  background: none;
  border: none;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  padding: 4px;
  transition: color 0.2s;
}

.link-reply__operation-item:hover {
  color: #007bff;
}

.link-reply__operation-desc {
  margin-left: 4px;
  font-size: 12px;
}
.reply-preview {
  background: #f5f7f9;
  padding: 12px;
  margin: 10px 0;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.preview-content {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
}

.reply-target {
  color: #007bff;
  font-weight: 500;
  white-space: nowrap;
}

.original-comment {
  color: #666;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  flex: 1;
}

.cancel-reply {
  background: none;
  border: none;
  color: #999;
  font-size: 18px;
  cursor: pointer;
  padding: 0 6px;
  margin-left: 8px;
}

.like-icon {
  width: 18px;
  height: 18px;
  vertical-align: middle;
  margin-right: 4px;
}

.link-reply__operation-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 顶部导航栏 */
.top-bar {
  margin-bottom: 12px;
}
.back-btn {
  background: none;
  border: none;
  color: #007bff;
  font-size: 16px;
  cursor: pointer;
}

.comment-title-wrapper {
  padding: 8px 12px;
  border-radius: 6px;
  margin: 24px 0 12px;
  background-color: rgba(250, 250, 250, 0.6); /* 浅灰+透明感 */
  backdrop-filter: blur(2px); /* 可选：让背景有毛玻璃效果 */
}

.comment-title {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.follow-btn.followed {
  background-color: #e0e0e0;
  color: #666;
  cursor: default;
}

.custom-dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.custom-dialog {
  background-color: #fff;
  color: #000;
  padding: 20px 30px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  min-width: 280px;
  text-align: center;
}

.dialog-text {
  font-size: 16px;
  margin-bottom: 20px;
}

.dialog-buttons {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.confirm-btn,
.cancel-btn {
  flex: 1;
  padding: 10px;
  font-size: 14px;
  border-radius: 6px;
  cursor: pointer;
  border: none;
  transition: 0.2s;
}

.confirm-btn {
  background-color: #000;
  color: #fff;
}

.cancel-btn {
  background-color: #fff;
  color: #000;
  border: 1px solid #ccc;
}

.cancel-btn:hover {
  background-color: #f0f0f0;
}

.confirm-btn:hover {
  opacity: 0.9;
}

.custom-dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.custom-dialog {
  background-color: #fff;
  color: #000;
  padding: 20px 30px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  min-width: 280px;
  text-align: center;
}

.dialog-text {
  font-size: 16px;
  margin-bottom: 20px;
}

.dialog-buttons {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.confirm-btn,
.cancel-btn {
  flex: 1;
  padding: 10px;
  font-size: 14px;
  border-radius: 6px;
  cursor: pointer;
  border: none;
  transition: 0.2s;
}

.confirm-btn {
  background-color: #000;
  color: #fff;
}

.cancel-btn {
  background-color: #fff;
  color: #000;
  border: 1px solid #ccc;
}

.cancel-btn:hover {
  background-color: #f0f0f0;
}

.confirm-btn:hover {
  opacity: 0.9;
}
.more-btn {
  font-size: 20px;
  color: #999;
  margin-left: 12px;
  cursor: pointer;
}
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
